<template>
  <el-form :model="formData" ref="vForm" :rules="rules" label-position="top" label-width="80px" size="default" @submit.prevent>
    <el-form-item label="用户名" prop="">
      <el-input v-model="userId" type="text" clearable></el-input>
    </el-form-item>
    <el-form-item label="房间" prop="">
      <el-input v-model="roomId" type="text" clearable></el-input>
    </el-form-item>
    <el-form-item>
      <!-- getFacility -->
      <el-button @click="getFacility" type="primary">授权</el-button>
      <el-button @click="handleJoin" type="primary">加入</el-button>
      <el-button @click="handleRemove" type="warning">离开</el-button>
    </el-form-item>
  </el-form>
  <div class="main-box" id="local"></div>
  <div class="video">
    <div v-for="(item, i) in remoteStream" :key="i" class="video-box">
      <div :class="item ? 'distant-stream' : ''" v-html="item"></div>
    </div>
  </div>
</template>

<script>
import { defineComponent, toRefs, reactive, nextTick, getCurrentInstance } from 'vue'
import TRTC from 'trtc-js-sdk'
import { genTestUserSig } from './utils/generateTestUserSig'
export default defineComponent({
  components: {},
  props: {},
  setup() {
    const state = reactive({
      sdkAppId: '你的sdkAppId',
      userId: 'user_' + Date.now(),
      secretKey: '你的secretKey',
      roomId: 8888,
      remoteStream: [],
    })
    let localClient = null
    let localStream = null

    // 创建房间
    const handleJoin = async () => {
      let { sdkAppId, userSig } = genTestUserSig({
        sdkAppId: parseInt(state.sdkAppId, 10),
        userId: state.userId,
        secretKey: state.secretKey,
      })
      localClient = TRTC.createClient({
        sdkAppId,
        userSig,
        userId: state.userId,
        mode: 'rtc',
      })
      installEventHandlers()
      try {
        await localClient.join({ roomId: state.roomId })
        console.log('进房成功')
      } catch (error) {
        console.error('进房失败 ' + error)
      }
      await createLocalStream()
      await localClient.publish(localStream)
    }
    // 创建本地音视频流
    const createLocalStream = async () => {
      try {
        localStream = TRTC.createStream({
          userId: state.userId,
          audio: true,
          video: true,
        })
        await localStream.initialize()
        localStream.setVideoProfile('1080p')
        localStream.play('local')
      } catch (error) {
        console.error('初始化本地流失败 ' + error)
      }
    }
    // 安装事件处理程序
    const installEventHandlers = () => {
      localClient.on('stream-added', (event) => {
        const remoteStream = event.stream
        //订阅远端流
        localClient.subscribe(remoteStream)
      })
      localClient.on('stream-subscribed', (event) => {
        const remoteStream = event.stream
        const base = `<div id="${'remote_stream-' + remoteStream.getId()}"  style="width:100%;height:100%"></div>`
        state.remoteStream.push(base)
        nextTick(() => {
          remoteStream.play('remote_stream-' + remoteStream.getId())
        })
      })
    }
    // 离开房间
    const handleRemove = async () => {
      localStream.stop()
      localStream.close()

      await localClient.unpublish(localStream)
      await localClient.leave()
      proxy.$message.warning('您已离开直播间')
    }
    // 音频授权
    const getFacility = () => {
      navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then((res) => {
        res.getTracks().forEach((track) => track.stop())
      })
    }
    return {
      handleJoin,
      handleRemove,
      getFacility,
      ...toRefs(state),
    }
  },
})
</script>

<style lang="scss">
.el-input-number.full-width-input,
.el-cascader.full-width-input {
  width: 100% !important;
}

.el-form-item--medium {
  .el-radio {
    line-height: 36px !important;
  }

  .el-rate {
    margin-top: 8px;
  }
}

.el-form-item--small {
  .el-radio {
    line-height: 32px !important;
  }

  .el-rate {
    margin-top: 6px;
  }
}

.el-form-item--mini {
  .el-radio {
    line-height: 28px !important;
  }

  .el-rate {
    margin-top: 4px;
  }
}

.clear-fix:before,
.clear-fix:after {
  display: table;
  content: '';
}

.clear-fix:after {
  clear: both;
}

.float-right {
  float: right;
}
</style>

<style lang="scss" scoped>
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    td.table-cell {
      display: table-cell;
      height: 36px;
      border: 1px solid #e1e2e3;
    }
  }
}

div.tab-container {
}

.label-left-align :deep(.el-form-item__label) {
  text-align: left;
}

.label-center-align :deep(.el-form-item__label) {
  text-align: center;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}

.custom-label {
}

.static-content-item {
  min-height: 20px;
  display: flex;
  align-items: center;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }
}

.main-box {
  width: 100%;
  height: 300px;
  border: 2px solid olivedrab;
}
.video {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.video-box {
  width: 49%;
}
.distant-stream {
  width: 100%;
  height: 200px;
  border: 2px solid olivedrab;
}
</style>
